package org.lqk.file.transfer.client;

import org.lqk.file.transfer.Constant;
import org.lqk.file.transfer.client.netty.NettyRemotingClient;
import org.lqk.file.transfer.protocol.CmdCode;
import org.lqk.file.transfer.protocol.FileTaskRequest;
import org.lqk.file.transfer.protocol.RemotingCommand;
import org.lqk.file.transfer.protocol.RpcType;
import org.lqk.file.transfer.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2015/9/1.
 */
public class FileClient {

	private final NettyRemotingClient client;
	private final static Logger log = LoggerFactory.getLogger(FileClient.class);
	public FileClient() {
		client = new NettyRemotingClient();
	}

	public void start() {
		client.start();
	}

	public void sendFile(String filePath, final String addr) throws IOException {
		RemotingCommand command = new RemotingCommand(CmdCode.File_Task.getCode(), RpcType.File_Request.getCode(), false,RemotingCommand.autoIncrement());
		FileTaskRequest request = new FileTaskRequest();
		final File file = new File(filePath);
		request.setFilePath(filePath);
		request.setFileName(file.getName());
		request.setBlockSize(Constant.BLOCK_SIZE);
		request.setFileSize(file.length());
		request.setMd5(MD5Util.md5(file));
		command.setBody(request);
		log.debug("invokeAsync command {}",JSON.toJSONString(command));
		client.invokeAsync(addr, command, 10 * 1000, requestFuture -> {
			log.debug("invokeAsync return");
		});
	}
}
